package com.wuxiaoqin.server.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuxiaoqin.server.entity.SecurityUsers;
import com.wuxiaoqin.server.entity.Users;

import com.wuxiaoqin.server.mapper.UsersMapper;
import com.wuxiaoqin.server.service.IUsersService;

import com.wuxiaoqin.uitls.respObj.RespBean;
import com.wuxiaoqin.uitls.util.DateUtil;
import com.wuxiaoqin.uitls.util.JwtTokenUtil;
import com.wuxiaoqin.uitls.util.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-10-22
 */
@Service

public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    /**
     * 当什么也没有配置的时候，账号和密码是由 Spring Security 定义生成的。而在实际项目中
     * 账号和密码都是从数据库中查询出来的。 所以我们要通过自定义逻辑控制认证逻辑。
     * 如果需要自定义逻辑时，只需要实现 UserDetailsService 接口即可
     */


    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired(required = false)
    private UsersMapper usersMapper;



    /**
     * 登录之后返回token
     *
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) throws InvalidKeySpecException, NoSuchAlgorithmException {
        String id = request.getSession().getId();
        System.out.println("sessioniduserserver:"+id);
//        Object attribute = request.getSession().getAttribute("captcha");
//        System.out.println("1111:"+attribute);

       String captcha = (String) request.getSession().getAttribute("captcha");
        System.out.println(captcha);
        if (code.isEmpty()||!captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码输入错误，请重新输入");
        }
        UserDetails userDetails = null;
        try{
            userDetails = userDetailsService.loadUserByUsername(username);
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.error("手机号码不存在");
        }
        Users user = getUsersByUserPhone(username);
        System.out.println(userDetails.getPassword());
        if (userDetails == null || !passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("密码不正确");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //System.out.println(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        return RespBean.success("登录成功",tokenMap);

    }

    /**
     * 注册
     * @param username
     * @param email
     * @param phone
     * @param password
     * @param request
     * @return
     */
    @Override
    public RespBean register(String username, String email, String phone, String password, HttpServletRequest request) throws InvalidKeySpecException, NoSuchAlgorithmException {

        System.out.println(username.length());
        if(username.equals("") || email.equals("") || password.equals("") || phone.equals("")){
            return RespBean.error("填写信息不全");
        }
        Users user = getUsersByUserPhone(phone);
        if (user != null) {
            return RespBean.error("手机号已存在，注册失败!");
         }
        Map<String, String> keyMap = RSAUtils.createKeys(512);
        String  publicKey = keyMap.get("publicKey");
        String  privateKey = keyMap.get("privateKey");
        //公钥加密
        String encodedData = RSAUtils.publicEncrypt(password, RSAUtils.getPublicKey(publicKey));
        String date = DateUtil.ptfDate();
        usersMapper.insertUser(username,email,phone,encodedData,privateKey,date);
        return RespBean.success("注册成功");
    }
    /**
     * 根据用户名获取用户
     * @param uPhone
     * @return
     */
    @Override
    public Users getUsersByUserPhone(String uPhone) {
        return usersMapper.selectOne(new QueryWrapper<Users>().eq("U_phone", uPhone));
    }

    /**
     * 验证手机号是否存在
     * @param phone
     * @return
     */
    @Override
    public RespBean ifHaveName(String phone) {

        Users user = getUsersByUserPhone(phone);
        if (user != null) {
            return RespBean.error("手机号已存在，注册失败!");
        }else {
            return RespBean.success("手机号没问题");
        }
    }

    /**
     * 修改用户密码
     * @param orgPass
     * @return
     */
    @Override
    public RespBean passmod( String orgPass,String newPass) throws InvalidKeySpecException, NoSuchAlgorithmException {
        Users user = getCurrentUser();
        //通过解密得到密码
        String dbOrgPassword = RSAUtils.privateDecrypt(user.getUPswd(), RSAUtils.getPrivateKey(user.getPrivatekey()));
        if (orgPass == null || !dbOrgPassword.equals(orgPass)){
            return RespBean.error("原密码输入有误！");
        }
        //重新加密
        Map<String, String> keyMap = RSAUtils.createKeys(512);
        String  publicKey = keyMap.get("publicKey");
        String  privateKey = keyMap.get("privateKey");
        //公钥加密
        String encodedData = RSAUtils.publicEncrypt(newPass, RSAUtils.getPublicKey(publicKey));
        String phone = user.getUPhone();
        usersMapper.passmod(phone,encodedData,privateKey);
        return RespBean.success("密码修改成功");
    }

    /**
     * 修改用户信息
     * @param name
     * @param sex
     * @param email
     * @param signature
     * @return
     */
    @Override
    public RespBean userInfoModify(String name, String sex, String email, String signature) {
        if (name == null||sex==null||email==null||signature == null){
            return RespBean.error("用户信息不能为空");
        }

        Integer sexdb ;
        if ("男".equals(sex)){
            sexdb=0;
        }else {
            sexdb=1;
        }
        usersMapper.userInfoModify(getCurrentUser().getUId(),name,sexdb,email,signature);
        return RespBean.success("修改成功");
    }

    /**
     * 获取当前用户
     * @return
     */
    @Override
    public Users getCurrentUser() {
        // 标识
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUsers securityUsers =(SecurityUsers) authentication.getPrincipal();
        return securityUsers.getUmsMember();
    }


    public Users getUsersByUserName2(String uName) {
        return usersMapper.getAcct(uName);
    }


}
